package com.yc.dao;

import com.yc.bean.OpType;
import com.yc.bean.Oprecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.util.List;

/**
 * @author zwei
 * @create 2024-08-07 17:18
 */
@Repository
public class OpRecordDaoImpl implements OpRecordDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

//    @Autowired
//    public void init(DataSource dataSource) {
//        this.jdbcTemplate = new JdbcTemplate(dataSource);
//    }

    @Override
    public void insertOpRecord(Oprecord oprecord) {
        String sql = "insert into oprecord (accountid,opmoney,optime,optype,transferid) values (?,?,now(),?,?)";
        this.jdbcTemplate.update(sql, oprecord.getAccountid(), oprecord.getOpmoney(), oprecord.getOptype().getKey(), oprecord.getTransferid());
    }

    @Override
    public List<Oprecord> findOpRecord(int accountid) {
        String sql = "select*from oprecord where accountid=? order by optime desc";
        List<Oprecord> list = this.jdbcTemplate.query(sql, (rs, rowNum) -> {
            Oprecord oprecord = new Oprecord();
            oprecord.setId(rs.getInt(1));
            oprecord.setAccountid(rs.getInt(2));
            oprecord.setOpmoney(rs.getDouble(3));
            oprecord.setOptime(rs.getString(4));
            String optype = rs.getString(5);
            if (optype.equalsIgnoreCase("withdraw")){
                oprecord.setOptype(OpType.WITHDRAW);
            } else if (optype.equalsIgnoreCase("deposit")) {
                oprecord.setOptype(OpType.DEPOSITE);
            } else {
                oprecord.setOptype(OpType.TRANSFER);
            }
            oprecord.setTransferid(rs.getInt(6));
            return oprecord;
        }, accountid);
        return list;
    }

    @Override
    public List<Oprecord> findOpRecord(int accountid, String opType) {
        String sql = "select*from oprecord where accountid=? and optype=? order by optime desc";
        List<Oprecord> list = this.jdbcTemplate.query(sql, (rs, rownum) -> {
            Oprecord oprecord = new Oprecord();
            oprecord.setId(rs.getInt(1));
            oprecord.setAccountid(rs.getInt(2));
            oprecord.setOpmoney(rs.getDouble(3));
            oprecord.setOptime(rs.getString(4));
            String optype = rs.getString(5);
            if (optype.equalsIgnoreCase("withdraw")) {
                oprecord.setOptype(OpType.WITHDRAW);
            } else if (optype.equalsIgnoreCase("deposit")) {
                oprecord.setOptype(OpType.DEPOSITE);
            } else {
                oprecord.setOptype(OpType.TRANSFER);
            }
            oprecord.setTransferid(rs.getInt(6));
            return oprecord;
        },accountid, opType);
        return list;
    }

    @Override
    public List<Oprecord> findOpRecord(Oprecord oprecord) {
        return null;
    }
}
